﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MongoDB.Bson;
using MongoDB.Driver;

using RexToy.Configuration;

using Monitor.Core.Entity;

namespace Monitor.Core
{
    public class DataReader
    {
        private const string MONGO = "mongo";
        private const string MONITOR = "monitor";
        private const string HISTORY = "history";
        private const string LATEST = "latest";
        private const string ERROR = "error";

        private MongoDatabase _db;

        public DataReader()
        {
            var cnnstr = AppConfig.Config.ReadValue(MONGO, MONITOR);
            MongoClient c = new MongoClient(cnnstr);
            var svr = c.GetServer();
            _db = svr.GetDatabase(MONITOR);
        }

        public IEnumerable<SensorResult> ReadLatest()
        {
            var list = new List<SensorResult>();
            var coll = _db.GetCollection(LATEST);
            var cursor = coll.FindAll();
            foreach (var d in cursor)
            {
                var sr = new SensorResult();
                sr.Id = (int)d["sid"];
                sr.Status = RexToy.EnumEx.Parse<ServiceStatus>((string)d["status"]);
                sr.Description = (string)d["description"];
                sr.LastRefresh = (DateTime)d["time"];
                sr.Error = (string)d["detail"];
                list.Add(sr);
            }
            return list;
        }
    }
}
